package com.poker.service;

import com.poker.entity.Permission;
import com.poker.repository.PermissionRepository;
import com.poker.util.Misc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionService {

    @Autowired
    private PermissionRepository repository;

    public void deleteById(String id) { repository.deleteById(id); }

    public List<Permission> findAll() {
        return repository.findAll();
    }

    public Permission getById(String id) {
        return repository.getOne(id);
    }

    public void save(Permission sysPermission) {
        repository.save(sysPermission);
    }
    
    /**
     * @param: [page, size];
     * @return: org.springframework.data.domain.Page<Permission>;
     * @Description: 不带条件分页查询;
     */
    public Page<Permission> findPermissionNoCriteria(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "id");
        return repository.findAll(pageable);
    }

    /**
     * @param: [page, size, permission];
     * @return: org.springframework.data.domain.Page<Permission>;
     * @Description: 带条件分页查询;
     */
    public Page<Permission> findPermissionCriteria(Integer page, Integer size, Permission permission) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "id");

        return repository.findAll((Specification<Permission>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            if (Misc.isNotEmpty(permission.getName()))
                list.add(criteriaBuilder.equal(root.get("name").as(String.class), permission.getName()));
            if (Misc.isNotEmpty(permission.getPermission()))
                list.add(criteriaBuilder.equal(root.get("permission").as(String.class), permission.getPermission()));

            Predicate[] predicateArray = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(predicateArray));
        }, pageable);
    }

}
